package com.action;

import com.bean.Record;
import com.bean.User;

import com.dao.UserDAO;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;
import java.util.Random;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import javax.faces.event.ComponentSystemEvent;

import javax.servlet.http.HttpServletRequest;


import org.primefaces.event.FileUploadEvent;

import org.primefaces.event.SelectEvent;


@ManagedBean(name = "user")
@SessionScoped
public class UserAction implements Serializable {
    @SuppressWarnings("compatibility:7009203087269969523")
    private static final long serialVersionUID = 1L;

    public UserAction() {
        super();
        listLevel = new ArrayList<Level>();
        listLevel.add(new Level(0, "Choose.."));
        listLevel.add(new Level(1, "Staff"));
        listLevel.add(new Level(2, "Leader"));
        listLevel.add(new Level(3, "Admin"));
        System.out.println("Nao thi test" + recordBean.getTotalRec());

    }

    ArrayList<Level> listLevel;
    private User userBean = new User();
    private ArrayList<User> list;
    private Record recordBean = new Record();
    private String search;


    public void setSearch(String search) {
        this.search = search;
    }

    public String getSearch() {
        return search;
    }


    public void handleFileUpload(FileUploadEvent event) {
        String path = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/Images/");


        Random rd = new Random();
        Long ran;
        ran = rd.nextLong();

        Long prefix = ran;
        if (ran < 0) {
            prefix = (-ran);
        }


        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
        String image =
            fmt.format(new Date()) + prefix.toString() + event.getFile().getFileName().substring(event.getFile().getFileName().lastIndexOf('.'));

        File result = new File(path + "\\" + image);
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(result);
            byte[] buffer = event.getFile().getContents();
            int bulk;
            InputStream inputStream = event.getFile().getInputstream();
            while (true) {
                bulk = inputStream.read(buffer);
                if (bulk < 0) {
                    break;
                }
                fileOutputStream.write(buffer, 0, bulk);
                System.out.println("Uploaded");
                fileOutputStream.flush();
            }
            //save url image
            image = "resources/images/" + image;
            userBean.setImage(image);
            fileOutputStream.close();
            inputStream.close();
            FacesMessage msg =
                new FacesMessage("File Description", "file name: " + event.getFile().getFileName() + "<br/>file size: " +
                                 event.getFile().getSize() / 1024 + " Kb<br/>content type: " +
                                 event.getFile().getContentType() + "<br/><br/>The file was uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } catch (Exception e) {
            e.printStackTrace();
            FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, "The files were not uploaded!", "");
            FacesContext.getCurrentInstance().addMessage(null, error);
        }
    }


    public void setListLevel(ArrayList<Level> listLevel) {
        this.listLevel = listLevel;
    }

    public ArrayList<Level> getListLevel() {
        return listLevel;
    }


    // Ham su ly so du lieu ra autocomplete

    public ArrayList<String> complete(String query) {
        ArrayList<String> suggest = new ArrayList<String>();
        UserDAO ud = new UserDAO();
        list = ud.getAll();

        for (User p : list) {

            //Neu tu khoa nhap vao giong voi username hoac email
            if (p.getUsername().startsWith(query) || p.getEmail().startsWith(query))
                suggest.add(p.getUsername() + ", " + p.getEmail() + ", " + p.getGender() + ", " + p.getCountry());
        }
        ArrayList<String> result = new ArrayList<String>();
        if (suggest.size() <= 3) {
            for (int i = 0; i < suggest.size(); i++) {
                result.add(suggest.get(i));
            }
        } else {
            for (int i = 0; i < 3; i++) {
                result.add(suggest.get(i));
            }
        }
        recordBean.setTotalRec(1);
        recordBean.setFirstRec(1);
        recordBean.setLastRec(1);
        recordBean.checkPrevousButton();
        recordBean.checkNextButton();
        return result;
    }

    //Tim kiem theo username

    public void Search(SelectEvent event) {
        //Lay ve du lieu duoc nhap vao autocomplete
        String paramString = (String)event.getObject();
        char ch[] = paramString.toCharArray();
        String username = "";
        char tmp[] = new char[50];
        //Xu ly lay ra username
        for (int i = 0; i <= ch.length; i++) {
            if (ch[i] == ',')
                break;
            else {
                tmp[i] = ch[i];
            }

        }
        username = new String(tmp);
        //Lay ra ban ghi co username dc nhap
        User ua = new UserDAO().getByUsername(username.trim());
        //Xoa danh sach hien tai
        list.clear();
        list.add(ua);
    }


    //insert User

    public String addUser() {
        String result = "error";
        UserDAO ud = new UserDAO();
        System.out.print("------- Test AddUser");
        if (ud.insert(userBean)) {
            recordBean.getFirstRec();
            recordBean.getLastRec();
            list = ud.getAll(recordBean);
            recordBean.increaseTotalRec();
            //Tao ra bien request
            FacesContext ctx = FacesContext.getCurrentInstance();
            HttpServletRequest req = (HttpServletRequest)ctx.getExternalContext().getRequest();

            //tao 1 session
            req.getSession().setAttribute("sessionName", userBean.getUsername());
            result = "insertsuccess";
        }
        return result;
    }


    //Hien thi list User

    public String listUser() {
        UserDAO ud = new UserDAO();
        list = ud.getAll(recordBean);
        return "success";
    }

    //Hien thong tin  User can sua

    public String editUser() {
        System.out.print("Edit user");
        System.out.println("Nao thi test" + recordBean.getTotalRec());
        System.out.println("Nao thi test" + recordBean.getCheckNextButton());
        UserDAO ud = new UserDAO();

        //Lay ve tham so idUpdate cua request
        String _id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("idUpdate");
        User ua = ud.getById(Integer.parseInt(_id));
        userBean.setUsername(ua.getUsername());
        userBean.setEmail(ua.getEmail());
        userBean.setGender(ua.getGender());
        userBean.setEmail(ua.getEmail());
        userBean.setPassword(ua.getPassword());
        userBean.setCountry(ua.getCountry());
        userBean.setLevelemp(ua.getLevelemp());
        userBean.setId(ua.getId());
        return "success";
    }

    //Sua thong tin User

    public String updateUser() {
        UserDAO ud = new UserDAO();
        User ua = new User();

        //Lay ve tham so idEdit cua Request
        String _id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("idEdit");
        ua.setId(Integer.parseInt(_id));
        ua.setUsername(userBean.getUsername());
        ua.setEmail(userBean.getEmail());
        ua.setPassword(userBean.getPassword());
        ua.setGender(userBean.getGender());
        ua.setCountry(userBean.getCountry());
        ua.setLevelemp(userBean.getLevelemp());
        ud.updateUser(ua);
        list = ud.getAll(recordBean);
        return "success";
    }

    //Xoa User

    public String deleteUser() {
        UserDAO ud = new UserDAO();

        //Lay ve tham so idDelete cua Request
        String _id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("idDelete");
        if (ud.delete(Integer.parseInt(_id))) {
            list = ud.getAll(recordBean);
        }

        return null;
    }


    // Login

    public String login() {
        String result = "error";
        UserDAO ud = new UserDAO();


        //Kiem tra username va password
        System.out.println("----------" + userBean.getUsername());
        
        if (ud.checkLogin(userBean)) {
            list = ud.getAll(recordBean);
            FacesContext ctx = FacesContext.getCurrentInstance();
            HttpServletRequest req = (HttpServletRequest)ctx.getExternalContext().getRequest();
            //Tao 1 session moi
            req.getSession().setAttribute("sessionName", userBean.getUsername());
            userBean.setLevelemp(userBean.getLevelemp());
            recordBean.checkNextButton();
            recordBean.checkPrevousButton();
            System.out.println("Nao thi test" + recordBean.getTotalRec());
            System.out.println("Nao thi test" + recordBean.getCurrentPage());
            System.out.println("Nao thi test" + recordBean.getRecordOnPage());
            System.out.println("Nao thi test" + recordBean.getCheckNextButton());
            result = "success";

        }
        return result;
    }

    //Logout

    public void logout() {
        FacesContext ctx = FacesContext.getCurrentInstance();
        HttpServletRequest req = (HttpServletRequest)ctx.getExternalContext().getRequest();
        req.getSession().removeAttribute("sessionName");
        try {
            ctx.getExternalContext().redirect("loginTest.jsf");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //Ham chuyen trang

    public void doRedirect(String url) {
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            context.getExternalContext().redirect("loginTest.jsf");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //Ham kiem tra phien lam viec

    public void verifyUseLogin(ComponentSystemEvent event) {
        FacesContext ctx = FacesContext.getCurrentInstance();
        HttpServletRequest req = (HttpServletRequest)ctx.getExternalContext().getRequest();

        // Kiem tra session
        if (req.getSession().getAttribute("sessionName") == null) {
            doRedirect("loginTest.jsf");
        }
    }

    //Ham xu ly nut next khi hien thi danh sach user

    public String next() {
        String result = "next";
        int allPage;

        //        //Kiem tra neu tong so ban ghi chia het cho so ban ghi hien thi tren 1 trang
                
        //
        //        //Kiem tra neu trang hien tai nho hon tong so trang thi moi enable nut Next
        //        if (currentPage < allPage) {
        //            //Neu trang hien tai bang tong so trang - 1
        //            //thi bien check nut Next se duoc gan bang 0 de trong request sau se disable nut Next
        //
        //            if (currentPage == (allPage - 1)) {
        //                checkNext = 0;
        //            }

        recordBean.nextCurrentPage();
        recordBean.getFirstRec();
        recordBean.getLastRec();
        UserDAO ud = new UserDAO();
        list = ud.getAll(recordBean);
        recordBean.checkPrevousButton();
        recordBean.checkNextButton();
        return result;
    }


    //Ham xu ly nut previous khi hien thi danh sach user

    public String previous() {
        String result = "previous";
        recordBean.previousCurrentPage();
        recordBean.getFirstRec();
        recordBean.getLastRec();
        UserDAO ud = new UserDAO();
        list = ud.getAll(recordBean);
        recordBean.checkPrevousButton();
        recordBean.checkNextButton();


        return result;
    }


    public void setUserBean(User userBean) {
        this.userBean = userBean;
    }

    public User getUserBean() {
        return userBean;
    }

    public void setList(ArrayList<User> list) {
        this.list = list;
    }

    public ArrayList<User> getList() {
        return list;
    }


    public void setRecordBean(Record recordBean) {
        this.recordBean = recordBean;
    }

    public Record getRecordBean() {
        return recordBean;
    }
}
